﻿using System;
using TeamTasker.Utils;
using TeamTasker.Server.DataAccess.Support;

namespace TeamTasker.Server.Service
{
    public class ApplicationInitializer
    {
        public string LogConfigPath { get; set; }
        public string LogOutputPath { get; set; }
        public string LogLevel { get; set; }  // DEBUG, INFO, WARN, ERROR
        public int LogsStorageSize { get; set; } // in MB

        public string BeanContainerConfigPath { get; set; }

        public void InitializeApplication()
        {
            Validate.NotBlank(LogConfigPath, "Path to log4net config is not specified");
            Validate.NotBlank(LogOutputPath, "Logs output path is not specified");
            Validate.NotBlank(LogLevel, "Log level is not specified");
            Validate.Positive(LogsStorageSize, "Logs storage size is not specified");
            Validate.NotBlank(BeanContainerConfigPath, "Path to bean container config is not specified");
            
            InitializeLogging();
            try
            {
                InitializeBeanContainer();
            }
            catch (Exception ex)
            {
                string msg = "Bean container initialization failed";
                Log.Error(msg, ex);
                throw new ApplicationException(msg, ex);
            }

            try
            {
                InitializeDictionaries();
            }
            catch (Exception ex)
            {
                string msg = "Dictionaries initialization failed";
                Log.Error(msg, ex);
                throw new ApplicationException(msg, ex);
            }
        }

        protected void InitializeLogging()
        {
            Log.Init(LogConfigPath, LogLevel, LogOutputPath, LogsStorageSize);
            Log.Debug("Logging initialization succeeded.");
        }

        protected void InitializeBeanContainer()
        {
            BeanFactory.Init(new string[] { BeanContainerConfigPath });
        }

        protected void InitializeDictionaries()
        {
            DictionaryRegistry registry = (DictionaryRegistry)
                BeanFactory.Instance.GetObject("dictionaryRegistry");
            registry.Init();
        }
    }
}
